package com.hust.chatvedio.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import androidx.fragment.app.Fragment;
import com.google.gson.Gson;
import com.hust.chatvedio.model.VideoBean;
import com.hust.chatvedio.R;
import com.hust.chatvedio.adapter.VideoAdapter;
import com.hust.chatvedio.utils.HttpUtils;

import java.util.ArrayList;
import java.util.List;

public class VedioFragment extends Fragment {
    ListView mainLv;
    String url = "http://baobab.kaiyanapp.com/api/v4/tabs/selected?udid=11111&vc=168&vn=3.3.1&deviceModel=Huawei6&first_channel=eyepetizer_baidu_market&last_channel=eyepetizer_baidu_market&system_version_code=20";
    List<VideoBean.ItemListBean> mDatas;
    private VideoAdapter adapter;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                String json = (String) msg.obj;
//                解析数据
                VideoBean videoBean = new Gson().fromJson(json,VideoBean.class);
//                过滤了不需要的数据
                List<VideoBean.ItemListBean> itemList = videoBean.getItemList();
                for (int i = 0; i < itemList.size(); i++) {
                    VideoBean.ItemListBean listBean = itemList.get(i);
                    if (listBean.getType().equals("video")) {
                        mDatas.add(listBean);
                    }
                }
//                提示适配器更新数据
                adapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_discovery, container, false);
        initView(view);
        setHasOptionsMenu(true);
        return view;
    }

    private void initView(View view) {

        mainLv = view.findViewById(R.id.main_lv);
        mDatas = new ArrayList<>();
        adapter = new VideoAdapter(getActivity(), mDatas);
        mainLv.setAdapter(adapter);

        loadData();
    }

    private void loadData() {
        /* 创建新的线程，完成数据的获取*/
        new Thread(new Runnable() {
            @Override
            public void run() {
                String jsonContent = HttpUtils.getJsonContent(url);
//                子线程不能更新UI，需要通过handler发送数据回到主线程
                Message message = new Message();   //发送的消息对象
                message.what = 1;
                message.obj = jsonContent;
                handler.sendMessage(message);
            }
        }).start();
    }


}
